package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketBrand;
import com.cskaoyan.market.service.MarketBrandService;
import com.cskaoyan.market.service.MarketBrandServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/brand/*")
public class AdminBrandController extends HttpServlet {

    private MarketBrandService brandService = new MarketBrandServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/brand/", "");
        if ("list".equals(op)) {
            list(req, resp);
        }
    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求参数
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String idParam = req.getParameter("id");
        String name = req.getParameter("name");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        Integer page = null;
        Integer limit = null;
        Integer id = null;
        try {
            if (idParam != null && idParam != "") {
                id = Integer.parseInt(idParam);
            }
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (NumberFormatException e) {
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.badArgument()));
            return;
        }

        //brand不应该从context中获取，应该直接从数据库获取
        List<MarketBrand> marketBrandList = brandService.list(page, limit, id, name, sort, order);

        //返回响应
        Object o = ResponseUtil.okList(marketBrandList);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(o));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op = requestURI.replace(req.getContextPath() + "/admin/brand/", "");
        if ("create".equals(op)) {
            create(req, resp);
        } else if ("update".equals(op)) {
            update(req, resp);
        } else if ("delete".equals(op)) {
            delete(req, resp);
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        System.out.println(requestBody);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        MarketBrand marketBrand = objectMapper.readValue(requestBody, MarketBrand.class);

        // 将数据更新到数据库中（逻辑删除）
        brandService.delete(marketBrand);
        // 响应
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok()));
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        System.out.println(requestBody);
        ObjectMapper objectMapper = JacksonUtil.getObjectMapper();
        MarketBrand marketBrand = objectMapper.readValue(requestBody, MarketBrand.class);

        // 将数据更新到数据库中
        brandService.update(marketBrand);
        // 返回响应
        Map<String, Object> data = new HashMap<>();
        data.put("id", marketBrand.getId());
        data.put("name", marketBrand.getName());
        data.put("desc", marketBrand.getDesc());
        data.put("picUrl", marketBrand.getPicUrl());
        data.put("floorPrice", marketBrand.getFloorPrice());
        data.put("addTime", marketBrand.getAddTime());
        data.put("updateTime", marketBrand.getUpdateTime());
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(data)));
    }

    private void create(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = req.getReader().readLine();
        System.out.println(requestBody);
        String name = JacksonUtil.parseString(requestBody, "name");
        String desc = JacksonUtil.parseString(requestBody, "desc");
        String floorPrice = JacksonUtil.parseString(requestBody, "floorPrice");
        String picUrl = JacksonUtil.parseString(requestBody, "picUrl");

        //校验
        if (StringUtils.isEmpty(name) || name.isEmpty()) {
            Object fail = ResponseUtil.fail(404, "品牌商名称不能为空");
            resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(fail));
            return;
        }

        // 需要创建对象
        MarketBrand marketBrand = new MarketBrand();
        marketBrand.setDeleted(false);
        marketBrand.setName(name);
        marketBrand.setDesc(desc);
        marketBrand.setFloorPrice(new BigDecimal(floorPrice));
        marketBrand.setPicUrl(picUrl);
        marketBrand.setSortOrder((byte)50);
        marketBrand.setAddTime(LocalDateTime.now());
        marketBrand.setUpdateTime(LocalDateTime.now());
        //将对象添加到数据库中
        brandService.create(marketBrand);

        // 返回响应
        Map<String, Object> data = new HashMap<>();
        data.put("id", marketBrand.getId());
        data.put("name", marketBrand.getName());
        data.put("desc", marketBrand.getDesc());
        data.put("picUrl", marketBrand.getPicUrl());
        data.put("floorPrice", marketBrand.getFloorPrice());
        data.put("addTime", marketBrand.getAddTime());
        data.put("updateTime", marketBrand.getUpdateTime());
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ResponseUtil.ok(data)));
    }
}
